import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/match/detail/zq_match_lineup_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/match_zq_utils.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/match_detail/soccer/zq_data_bottom_dialog.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';

import '../../../entity/match/zq_lineup_entity.dart';
import '../../../widgets/base/qkd_text.dart';

class ZqFirstTeamView extends StatefulWidget {
  const ZqFirstTeamView({super.key});

  @override
  State<ZqFirstTeamView> createState() => _ZqFirstTeamViewState();
}

class _ZqFirstTeamViewState extends State<ZqFirstTeamView> {
  List<double> homeX = [];
  List<double> homeY = [];
  List<double> guestX = [];
  final _soccerFieldHeight = (Get.width - 20) / 686 * 1330;
  final logic = Get.find<ZqMatchLineupLogic>();

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ZqMatchLineupLogic>(builder: (_) {
      return Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
        child: Column(
          children: [
            _lineupTitle(true),
            Stack(
              alignment: AlignmentDirectional.center,
              children: [
                Image.asset(Utils.getImgPath('zq_field.png'),
                    height: _soccerFieldHeight,
                    width: double.infinity,
                    fit: BoxFit.cover),
                if (logic.data?.homeCoachName.hasValue == true)
                  Positioned(
                    top: 8,
                    left: 13,
                    child: QkdText("教练：${logic.data?.homeCoachName?.trim()}",
                      fontSize: 10, color: Colours.grey66
                    )
                  ),
                if (logic.data?.isLastLineup == false &&
                    logic.data?.homeUmpire.hasValue == true)
                  Positioned(
                    top: 8,
                    right: 13,
                    child: QkdText("主裁判：${logic.data!.homeUmpire?.trim()}",
                      fontSize: 10
                    )
                  ),
                if (logic.data?.guestCoachName.hasValue == true)
                  Positioned(
                    bottom: 8,
                    left: 13,
                    child: QkdText("教练：${logic.data!.guestCoachName?.trim()}",
                      fontSize: 10, color: Colours.grey66
                    )
                  ),
                if (logic.data?.isLastLineup == false &&
                    logic.data?.guestUmpire.hasValue == true)
                Positioned(
                  bottom: 8,
                  right: 13,
                  child: QkdText("主裁判：${logic.data!.guestUmpire?.trim()}",
                    fontSize: 10,color: Colours.grey66
                  )
                ),
                Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(width: 13),
                      Flexible(
                        fit: FlexFit.tight,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            QkdText(logic.toArray(true),
                              fontSize: 10, color: Colours.grey66
                            ),
                            const SizedBox(height: 12),
                            QkdText(logic.toArray(false),
                              fontSize: 10, color: Colours.grey66
                            )
                          ],
                        ),
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          QkdText(logic.ageAndWorth(true),
                            fontSize: 10,
                            fontWeight: FontWeight.w300
                          ),
                          const SizedBox(height: 12),
                          QkdText(logic.ageAndWorth(false),
                            fontSize: 10,
                            color: Colours.text,
                            fontWeight: FontWeight.w300
                          )
                        ],
                      ),
                      Container(width: 13)
                    ]),
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: logic.data?.homeArray?.length == 5
                      ? _soccerFieldHeight / 2 + 5
                      : _soccerFieldHeight / 2,
                  child: Padding(
                    padding: const EdgeInsets.only(
                        top: 17, bottom: 20, left: 5, right: 5),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: getHomeLineup(),
                    ),
                  ),
                ),
                Positioned(
                  top: logic.data?.homeArray?.length == 5
                      ? _soccerFieldHeight / 2
                      : _soccerFieldHeight / 2,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Padding(
                    padding: const EdgeInsets.only(
                        top: 20, bottom: 20, left: 5, right: 5),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: getGuestLineup(),
                    ),
                  ),
                ),
              ],
            ),
            _lineupTitle(false)
            //Container(height: 14)
          ],
        ),
      );
    });
  }

  Widget _lineupTitle(bool isHome) {
    return Container(
      height: 34,
      color: isHome ? Colours.redE26257 : Colours.blue4E81DE,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Row(
        children: [
          Expanded(
              child: Row(mainAxisSize: MainAxisSize.min, children: [
            CachedNetworkImage(
                height: 18,
                width: 18,
                fit: BoxFit.fitHeight,
                placeholder: (context, url) => Styles.placeholderIcon(),
                errorWidget: (
                  context,
                  url,
                  error,
                ) =>
                    Image.asset(Utils.getImgPath("zq_placeholder.png")),
                imageUrl: (isHome
                        ? logic.detail.info?.baseInfo?.homeLogo
                        : logic.detail.info?.baseInfo?.guestLogo) ??
                    ""),
            Container(width: 5),
            QkdText(
              (isHome
                      ? logic.detail.info?.baseInfo?.homeName
                      : logic.detail.info?.baseInfo?.guestName) ??
                  "",
              fontSize: 10,fontWeight: FontWeight.w500,color: Colors.white
            )
          ]).alignStart),
          if (isHome)
            Expanded(
              flex: 2,
              child: QkdText(logic.data?.locationCn ?? "",
                fontSize: 10,fontWeight: FontWeight.w500,color: Colors.white
              ).center,
            ),
          Expanded(
            child: QkdText(logic.toArray(isHome),
              fontSize: 10,fontWeight: FontWeight.w500,color: Colors.white
            ).alignEnd
          )
        ],
      ),
    );
  }

  Widget _player(bool isHome, int index) {
    final player = isHome
        ? (logic.data?.homeLineup?[index])
        : logic.data?.guestLineup?[index];
    return GestureDetector(
      onTap: () {
        if (logic.data?.isLastLineup == true) {
          Get.bottomSheet(const ZqDataBottomDialog(),
            isScrollControlled: true,
            settings: RouteSettings(
            arguments: <int>[
              isHome ? (logic.data?.homeQxbMatchId ?? 0)
                : (logic.data?.guestQxbMatchId ?? 0),
              int.parse(player?.playerId ?? "0")
            ]
          ));
        } else {
          Get.bottomSheet(const ZqDataBottomDialog(),
              isScrollControlled: true,
              settings: RouteSettings(
                  arguments: <int>[
                    logic.data?.matchId ?? 0,
                    int.parse(player?.playerId ?? "0")
                  ]
              ));
        }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 60,
            height: 28,
            child: Stack(
              alignment: AlignmentDirectional.center,
              children: [
                Container(
                    alignment: Alignment.center,
                    clipBehavior: Clip.antiAlias,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                          width: 1.5,
                          color:
                              isHome ? Colours.main : Colours.blue2766D6),
                      color: isHome ? Colours.main : Colours.blue2766D6,
                    ),
                    width: 28,
                    height: 28,
                    child: ClipOval(
                      child: CachedNetworkImage(
                        width: 28,
                        height: 28,
                        fit: BoxFit.cover,
                        imageUrl: player?.playerLogo ?? "",
                        placeholder: (context, url) => Styles.placeholderIcon(),
                        errorWidget: (context, url, error) => Container(
                          alignment: Alignment.center,
                          child: QkdText(
                            '${player?.number}',
                            fontSize: 13,
                            color: Colours.white,
                            fontFamily: "Din",
                          ),
                        ),
                      ),
                    )),

                ///红黄牌
                Positioned(
                    top: 0, left: 13, child: _playerFlag(player?.playerId, 2)),
                ///角球
                Positioned(
                    top: 0, right: 13, child: _playerFlag(player?.playerId, 4)),
                ///进球点球乌龙
                Positioned(
                    bottom: 0,
                    left: 13,
                    child: _playerFlag(player?.playerId, 3)),
                ///上下场
                Positioned(
                    bottom: 0,
                    right: 13,
                    child: _playerFlag(player?.playerId, 0)),
                ///上下场时间
                logic.playerEvents?[player?.playerId]?[1].length != 0 &&
                        logic.playerEvents != null &&
                        logic.playerEvents?[player?.playerId] != null
                ? Positioned(
                  bottom: 0,
                  right: 0,
                  child: QkdText(
                    logic.playerEvents?[player?.playerId]?[1].trim() ?? "",
                    fontSize: 8,
                  )
                ) : Container()
              ],
            ),
          ),
          Container(height: 3),
          QkdText(
            (player?.nameCn ?? player?.nameEn) ?? '',
            fontSize: 9, fontWeight: FontWeight.w500,
            maxLines: 1,
            textAlign: TextAlign.center,
          ),
          Container(height: 1),
          (player?.rating == null ||
                  player?.rating == '' ||
                  player?.rating == '0.00')
              ? Container()
              : Container(
                  width: 25,
                  height: 12,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: isHome ? Colours.redEC8C81 : Colours.blue81A8EC),
                  child: QkdText(
                    player!.rating!,
                    color: Colours.white, fontSize: 8
                  ),
                )
        ],
      ),
    );
  }

  List<Widget> getHomeLineup() {
    final List<String> lineup =
        logic.data?.homeArray.noValue == true? ["4","2","3","1"] : logic.data!.homeArray!.split('');
    List<Widget> listChildren = [];
    List<Widget> listParent = [];
    int sum = 0;
    listParent.add(Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Flexible(flex: 1, fit: FlexFit.tight, child: _player(true, 0))
      ],
    ));
    for (int i = 0; i < lineup.length; i++) {
      i > 0 ? sum += int.parse(lineup[i - 1]) : sum = sum;
      for (int j = 0; j < int.parse(lineup[i]); j++) {
        int tag = sum + j + 1;
        listChildren.add(
            Flexible(flex: 1, fit: FlexFit.tight, child: _player(true, tag)));
      }
      listParent.add(Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: listChildren,
      ));
      listChildren = [];
    }
    return listParent;
  }

  List<Widget> getGuestLineup() {
    final lineup =
        logic.data?.guestArray.noValue == true? ["4","2","3","1"] : logic.data!.guestArray!.split('');
    List<Widget> listChildren = [];
    List<Widget> listParent = [];
    int sum1 = 0;
    for (int i = lineup.length - 1; i >= 0; i--) {
      i < lineup.length - 1 ? sum1 += int.parse(lineup[i + 1]) : sum1 = sum1;
      for (int j = 0; j < int.parse(lineup[i]); j++) {
        listChildren.add(Flexible(
            flex: 1,
            fit: FlexFit.tight,
            child: Container(
                alignment: Alignment.center,
                child: _player(
                    false, logic.data!.guestLineup!.length - 1 - (sum1 + j)))));
      }
      if (listChildren.length == 1) {
        listParent.add(Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: listChildren,
        ));
      } else {
        listParent.add(Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: listChildren,
        ));
      }
      listChildren = [];
    }
    listParent.add(Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Flexible(flex: 1, fit: FlexFit.tight, child: _player(false, 0))
      ],
    ));
    return listParent;
  }

  Widget _playerFlag(String? playerId, int index) {
    return logic.playerEvents?[playerId]?[index].length != 0 &&
            logic.playerEvents != null &&
            logic.playerEvents?[playerId] != null
        ? Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(width: 0.5, color: Colours.white),
            ),
            child: Image.asset(
                width: 12,
                height: 12,
                Utils.getImgPath(ZqLineupUtils.lineupIcon[ZqLineupUtils.title
                    .indexOf(logic.playerEvents?[playerId]?[index].trim())])))
        : Container();
  }
}
